<template>
  <div class="water-guardian">
    <!-- 水质监测站点 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>附近监测站点</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshStations">
              刷新
            </el-button>
          </div>
          <div class="station-list">
            <div v-if="monitorStations.length === 0" class="empty-stations">
              <el-empty description="暂无监测站点" :image-size="80"></el-empty>
            </div>
            <div v-else v-for="station in monitorStations" :key="station.id" class="station-item">
              <div class="station-info">
                <div class="station-name">{{ station.name }}</div>
                <div class="station-location">{{ station.location }}</div>
                <div class="water-quality">
                  <el-tag :type="getQualityType(station.quality)" size="small">
                    {{ station.quality }}
                  </el-tag>
                  <span class="quality-desc">{{ getQualityDesc(station.quality) }}</span>
                </div>
              </div>
              <div class="station-action">
                <el-button type="primary" size="mini" @click="reportWaterQuality(station)">
                  上报水质
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <div slot="header">
            <span>护水活动</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="getWaterActivities">
              刷新
            </el-button>
          </div>
          <div class="activity-list">
            <div v-if="waterActivities.length === 0" class="empty-activities">
              <el-empty description="暂无护水活动" :image-size="80"></el-empty>
            </div>
            <div v-else v-for="activity in waterActivities" :key="activity.id" class="activity-item">
              <div class="activity-icon">
                <i :class="getActivityIcon(activity.type)" :style="{color: getActivityColor(activity.type)}"></i>
              </div>
              <div class="activity-info">
                <div class="activity-title">{{ activity.title }}</div>
                <div class="activity-time">{{ formatDate(activity.date) }}</div>
                <div class="activity-location">{{ activity.location }}</div>
                <div class="activity-reward">奖励：+{{ activity.points }}分</div>
              </div>
              <div class="activity-action">
                <el-button
                  type="success"
                  size="mini"
                  @click="joinActivity(activity)"
                  :disabled="activity.status === '已结束'">
                  {{ activity.status === '已结束' ? '已结束' : '参与' }}
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 我的护水记录 -->
    <el-row style="margin-bottom: 20px;">
      <el-col :span="24">
        <el-card>
          <div slot="header">
            <span>我的护水记录</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="getWaterRecords">
              刷新记录
            </el-button>
          </div>
          <div v-if="myRecords.length === 0" class="empty-records">
            <el-empty description="暂无护水记录" :image-size="80"></el-empty>
          </div>
          <el-table v-else :data="myRecords" style="width: 100%">
            <el-table-column prop="date" label="日期" width="120">
              <template slot-scope="scope">
                {{ formatDate(scope.row.date) }}
              </template>
            </el-table-column>
            <el-table-column prop="activity" label="活动名称" width="150">
            </el-table-column>
            <el-table-column prop="type" label="活动类型" width="120">
            </el-table-column>
            <el-table-column prop="duration" label="参与时长">
            </el-table-column>
            <el-table-column prop="contribution" label="贡献描述">
            </el-table-column>
            <el-table-column prop="points" label="获得积分" width="100">
              <template slot-scope="scope">
                <span style="color: #67C23A;">+{{ scope.row.points }}分</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === '已完成' ? 'success' : 'warning'" size="small">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 护水统计 -->
    <el-row>
      <el-col :span="24">
        <el-card>
          <div slot="header">
            <span>护水统计</span>
          </div>
          <el-row :gutter="20" class="stats-row">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ totalActivities }}</div>
                <div class="stat-label">参与活动</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-value">{{ totalScore }}</div>
                <div class="stat-label">获得积分</div>
              </div>
            </el-col>
<!--            <el-col :span="6">-->
<!--              <div class="stat-item">-->
<!--                <div class="stat-value">{{ protectedWater }}</div>-->
<!--                <div class="stat-label">保护水源(L)</div>-->
<!--              </div>-->
<!--            </el-col>-->
<!--            <el-col :span="6">-->
<!--              <div class="stat-item">-->
<!--                <div class="stat-value">{{ cleanedArea }}</div>-->
<!--                <div class="stat-label">清理面积(㎡)</div>-->
<!--              </div>-->
<!--            </el-col>-->
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 水质上报对话框 -->
    <el-dialog title="水质问题上报" :visible.sync="reportDialogVisible" width="500px">
      <el-form :model="reportForm" :rules="reportRules" ref="reportForm" label-width="100px">
        <el-form-item label="监测站点" prop="stationId">
          <el-input v-model="reportForm.stationName" disabled></el-input>
        </el-form-item>
        <el-form-item label="问题类型" prop="issueType">
          <el-select v-model="reportForm.issueType" placeholder="请选择问题类型" style="width: 100%">
            <el-option label="水质污染" value="水质污染"></el-option>
            <el-option label="垃圾堆积" value="垃圾堆积"></el-option>
            <el-option label="异味问题" value="异味问题"></el-option>
            <el-option label="其他问题" value="其他问题"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述" prop="description">
          <el-input
            v-model="reportForm.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述发现的问题">
          </el-input>
        </el-form-item>
        <el-form-item label="紧急程度" prop="urgency">
          <el-radio-group v-model="reportForm.urgency">
            <el-radio label="一般">一般</el-radio>
            <el-radio label="紧急">紧急</el-radio>
            <el-radio label="非常紧急">非常紧急</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reportDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReport">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getWaterStations, getWaterActivities, joinWaterActivity, getWaterRecords, reportWaterIssue } from '@/api/credit/prosocial'

export default {
  name: "WaterGuardian",
  data() {
    return {
      monitorStations: [],
      waterActivities: [],
      myRecords: [],
      totalActivities: 0,
      totalScore: 0,
      protectedWater: 0,
      cleanedArea: 0,
      loading: false,
      reportDialogVisible: false,
      reportForm: {
        stationId: null,
        stationName: '',
        issueType: '',
        description: '',
        urgency: '一般'
      },
      reportRules: {
        issueType: [
          { required: true, message: '请选择问题类型', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请填写问题描述', trigger: 'blur' }
        ],
        urgency: [
          { required: true, message: '请选择紧急程度', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.getWaterStations();
    this.getWaterActivities();
    this.getWaterRecords();
  },
  methods: {
    /** 获取水质监测站点 */
    getWaterStations() {
      this.loading = true;
      getWaterStations().then(response => {
        if (response.code === 200) {
          this.monitorStations = response.data || [];
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 获取护水活动 */
    getWaterActivities() {
      this.loading = true;
      getWaterActivities().then(response => {
        if (response.code === 200) {
          this.waterActivities = response.data || [];
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 获取护水记录 */
    getWaterRecords() {
      this.loading = true;
      getWaterRecords().then(response => {
        if (response.code === 200) {
          this.myRecords = response.data || [];
          this.calculateWaterStats();
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 计算护水统计数据 */
    calculateWaterStats() {
      this.totalActivities = this.myRecords.length;
      this.totalScore = this.myRecords.reduce((sum, record) => sum + (record.points || 0), 0);
      this.protectedWater = this.myRecords.reduce((sum, record) => {
        const water = parseFloat(record.protectedWater) || 0;
        return sum + water;
      }, 0);
      this.cleanedArea = this.myRecords.reduce((sum, record) => {
        const area = parseFloat(record.cleanedArea) || 0;
        return sum + area;
      }, 0);
    },

    /** 刷新站点 */
    refreshStations() {
      this.getWaterStations();
      this.$message.success('站点信息已刷新');
    },

    /** 获取水质类型 */
    getQualityType(quality) {
      const typeMap = {
        '优': 'success',
        '良': 'warning',
        '差': 'danger'
      };
      return typeMap[quality] || 'info';
    },

    /** 获取水质描述 */
    getQualityDesc(quality) {
      const descMap = {
        '优': '水质良好，适合饮用',
        '良': '水质一般，需要关注',
        '差': '水质较差，需要治理'
      };
      return descMap[quality] || '未知';
    },

    /** 获取活动图标 */
    getActivityIcon(type) {
      const iconMap = {
        '河道清理': 'el-icon-brush',
        '水质监测': 'el-icon-monitor',
        '环保宣传': 'el-icon-megaphone',
        '植树造林': 'el-icon-tree'
      };
      return iconMap[type] || 'el-icon-water-cup';
    },

    /** 获取活动颜色 */
    getActivityColor(type) {
      const colorMap = {
        '河道清理': '#409EFF',
        '水质监测': '#67C23A',
        '环保宣传': '#E6A23C',
        '植树造林': '#F56C6C'
      };
      return colorMap[type] || '#909399';
    },

    /** 参与活动 */
    joinActivity(activity) {
      this.$confirm(`确认参与"${activity.title}"活动？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const joinData = {
          activityId: activity.id,
          activityType: 'water'
        };
        joinWaterActivity(joinData).then(response => {
          if (response.code === 200) {
            this.$message.success('活动参与成功！');
            this.getWaterActivities();
            this.getWaterRecords();
          } else {
            this.$message.error(response.msg || '参与失败');
          }
        }).catch(() => {
          this.$message.error('参与失败，请稍后重试');
        });
      });
    },

    /** 上报水质问题 */
    reportWaterQuality(station) {
      this.reportForm = {
        stationId: station.id,
        stationName: station.name,
        issueType: '',
        description: '',
        urgency: '一般'
      };
      this.reportDialogVisible = true;
    },

    /** 提交上报 */
    submitReport() {
      this.$refs.reportForm.validate((valid) => {
        if (valid) {
          const reportData = {
            stationId: this.reportForm.stationId,
            issueType: this.reportForm.issueType,
            description: this.reportForm.description,
            urgency: this.reportForm.urgency
          };
          reportWaterIssue(reportData).then(response => {
            if (response.code === 200) {
              this.$message.success('问题上报成功！');
              this.reportDialogVisible = false;
            } else {
              this.$message.error(response.msg || '上报失败');
            }
          }).catch(() => {
            this.$message.error('上报失败，请稍后重试');
          });
        }
      });
    },

    /** 格式化日期 */
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    }
  }
};
</script>

<style scoped>
.station-list {
  max-height: 300px;
  overflow-y: auto;
}

.empty-stations,
.empty-activities,
.empty-records {
  padding: 40px 0;
  text-align: center;
}

.station-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  margin-bottom: 10px;
  background-color: #fafafa;
}

.station-item:hover {
  border-color: #409EFF;
  background-color: #f0f9ff;
}

.station-info {
  flex: 1;
}

.station-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.station-location {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.water-quality {
  display: flex;
  align-items: center;
}

.quality-desc {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.station-action {
  margin-left: 15px;
}

.activity-list {
  max-height: 300px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  margin-bottom: 10px;
  background-color: #fafafa;
}

.activity-item:hover {
  border-color: #67C23A;
  background-color: #f0f9ff;
}

.activity-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin-right: 15px;
}

.activity-info {
  flex: 1;
}

.activity-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.activity-time {
  font-size: 14px;
  color: #606266;
  margin-bottom: 3px;
}

.activity-location {
  font-size: 12px;
  color: #909399;
  margin-bottom: 3px;
}

.activity-reward {
  font-size: 12px;
  color: #67C23A;
  font-weight: bold;
}

.activity-action {
  margin-left: 15px;
}

.stats-row {
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 20px;
  border-radius: 8px;
  background-color: #f8f9fa;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}
</style>
